<!-- 部门树 -->
<template>
  <el-card shadow="never" style="border: none" class="SelectPersonDialog">
    <el-input
      v-model="deptName"
      placeholder="组织机构"
      clearable
      class="mb-[10px]"
    >
      <template #prefix>
        <i-ep-search />
      </template>
    </el-input>
    <el-tree
      ref="deptTreeRef"
      node-key="id"
      :loading="loading"
      :data="deptList"
      :props="{ children: 'nodes', label: 'organizationName', disabled: '' }"
      :expand-on-click-node="false"
      :highlight-current="true"
      :check-on-click-node="true"
      :current-node-key="deptId"
      :filter-node-method="handleFilter"
      default-expand-all
      @node-click="handleNodeClick"
    />
  </el-card>
</template>

<script setup lang="ts">
import request from "@/utils/request";

const props = defineProps({
  modelValue: {
    type: [String],
    default: undefined,
  },
});

const deptList: any = ref([]); // 部门列表
const deptTreeRef = ref(ElTree); // 部门树
const deptName = ref(""); // 部门名称

const emits = defineEmits([
  "node-click",
  "update:modelValue",
  "finish-loading",
]);

const deptId = useVModel(props, "modelValue", emits);

watch(
  () => deptId,
  (newVal) => {
    if (!newVal.value) {
      deptTreeRef?.value?.setCurrentKey(null);
      deptName.value = "";
    }
  },
  {
    deep: true,
  }
);
watchEffect(
  () => {
    deptTreeRef.value.filter(deptName.value);
  },
  {
    flush: "post", // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);

/** 部门筛选 */
function handleFilter(value: string, data: any) {
  if (!value) {
    return true;
  }
  return data.organizationName.indexOf(value) !== -1;
}

/** 部门树节点 Click */
function handleNodeClick(data: { [key: string]: any }) {
  deptId.value = data.id;
  emits("node-click");
}

const loading = ref(false);
async function getOrganizations() {
  return new Promise<void>(async (resolve, reject) => {
    try {
      loading.value = true;
      const { data } = await request({
        url: "/system/sysOrganization/getUsableTree",
        method: "post",
        data: {},
      }).finally(() => {
        loading.value = false;
        emits("finish-loading", false);
      });
      resolve(data);
    } catch (e) {
      reject(e);
    }
  });
}

onBeforeMount(async () => {
  deptList.value = await getOrganizations();
});
</script>
<style lang="scss" scoped>
:deep(.el-tree) {
  overflow-x: scroll;
  .el-tree-node {
    width: fit-content;
    min-width: 100%;
  }
}
:deep(
    .el-tree--highlight-current
      .el-tree-node.is-current
      > .el-tree-node__content
  ) {
  color: rgb(0, 128, 255);
  border-radius: 6px;
  .el-tree-node__expand-icon {
    color: var(--el-menu-active-color);
  }
}
</style>
